using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Windows.Data;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Media3D;
using NewtonDynamics;


namespace WPFPhysics1
{
	public abstract class Body : CBody, INotifyPropertyChanged
	{
		protected Brush brush;
		protected Vector offset;
        public String bodyid;

		/// <summary>
		/// Constructor
		/// </summary>
		/// <param name="collision">Collision instance</param>
		public Body( CCollision collision, Brush brush ) : base( collision )
		{
			this.brush = brush;
			this.SetTransform += new EventHandler<CSetTransformEventArgs>( Body_SetTransform );
            App myapp = Application.Current as App;
            this.bodyid = myapp.nextBodyId();
		}

		/// <summary>
		/// Initialize collision and calculate inertial matrix
		/// </summary>
		/// <param name="collision"></param>
		/// <param name="modifierMatrix"></param>
		protected static CCollisionConvexPrimitives AddConvexHullModifier( CCollisionConvexPrimitives collision, Matrix3D modifierMatrix )
		{
			CCollisionConvexPrimitives modifier = collision.CreateConvexHullModifier();
			collision.Release();

			modifier.ConvexHullModifierMatrix = modifierMatrix;

			return modifier;
		}

		/// <summary>
		/// Handle Matrix changed callback
		/// </summary>
		/// <param name="sender">Body</param>
		/// <param name="e">Event arguments</param>
		void Body_SetTransform( object sender, CSetTransformEventArgs e )
		{
			Matrix3D m = Matrix;
			Matrix = new Matrix3D( (float)m.M11, (float)m.M12, 0, 0, (float)m.M21, (float)m.M22, 0, 0, 0, 0, 1, 0, (float)m.OffsetX, (float)m.OffsetY, 0, 0 );
			OnPropertyChanged( "DisplayMatrix" );
		}

		/// <summary>
		/// Calculate the display matrix
		/// </summary>
		/// <param name="m">XNA matrix</param>
		public static System.Windows.Media.Matrix GetDisplayMatrix( Matrix3D m, Vector offset )
		{
			return new Matrix( m.M11, m.M12, m.M21, m.M22, m.OffsetX + offset.X, m.OffsetY + offset.Y );
		}

		/// <summary>
		/// Get the display matrix
		/// </summary>
		public System.Windows.Media.Matrix DisplayMatrix
		{
			get { return GetDisplayMatrix( Matrix, offset ); }
		}

		/// <summary>
		/// Get the brush
		/// </summary>
		public Brush Brush
		{
			get { return brush; }
		}

        public String Bodyid { get { return bodyid; } }


		#region INotifyPropertyChanged Members

		/// <summary>
		/// Notify property changed
		/// </summary>
		/// <param name="propertyName">Property name</param>
		protected void OnPropertyChanged( string propertyName )
		{
			if ( PropertyChanged != null ) PropertyChanged( this, new PropertyChangedEventArgs( propertyName ) );
		}

		public event PropertyChangedEventHandler PropertyChanged;

		#endregion
	}
}